<script setup lang="ts" name="life-mall-order-list">
import type { VxeGridInstance, VxePagerEvents } from 'vxe-table'

import { orderListApi } from '@fl/api/city-service'
import { formatTime } from '@fl/utils'
import { cloneDeep } from 'lodash-es'
import { useRouter } from 'vue-router'

import type { IRowV0, ISkuOrderV0 } from './types'

import DeliveryDialog from './components/delivery-dialog.vue'
import ExpandBtn from './components/expand-btn.vue'
import ShipmentsDialog from './components/shipments-dialog.vue'
import { useDicts } from './hooks/use-dicts'
import { useForm } from './hooks/use-form'
import { useTable } from './hooks/use-table'

const { form, schema, state } = useForm()
const { childGridOptions, childTableColumns, gridOptions } = useTable()
const { getDictLabel } = useDicts()
const router = useRouter()

const showDelivery = ref<boolean>(false)
const showShipments = ref<boolean>(false)
const detailId = ref<number | string>('')
const detailData = ref<any>({})
const orderLineId = ref(0)

const xGrid = ref<VxeGridInstance<IRowV0>>()
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})

function getList() {
    gridOptions.loading = true

    const {
        goodsName,
        orderAfterSaleStatus,
        orderCode,
        orderDate,
        orderStatus,
    } = form.value
    let createTimeEnd, createTimeStart
    if (Array.isArray(orderDate)) {
        createTimeEnd = `${orderDate[1]} 23:59:59`
        createTimeStart = `${orderDate[0]} 00:00:00`
    }
    const oParams = {
        createTimeEnd,
        createTimeStart,
        like: goodsName,
        orderCode,
        orderStatus,
        page: tablePage.currentPage,
        size: tablePage.pageSize,
        statusType: orderAfterSaleStatus,
    }

    orderListApi(oParams).then((res) => {
        const { records, total } = res
        const formatList = records.map((rItem: IRowV0) => {
            return {
                ...rItem,
                isChildTableExpanded: false,
                isShowPhone: false,
            }
        })
        tablePage.total = total
        gridOptions.data = formatList
        nextTick(() => {
            expandAllRows()
        })
    }).finally(() => {
        gridOptions.loading = false
    })
}
getList()

watch(() => form.value.orderStatus, () => {
    search()
}, { deep: true })

function search() {
    tablePage.currentPage = 1
    getList()
}
function reset() {
    form.value = {
        ...state,
    }
    tablePage.currentPage = 1
    tablePage.pageSize = 10
    getList()
}
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
    getList()
}

// 展开所有行
function expandAllRows() {
    const $grid = xGrid.value
    if ($grid) {
        $grid.setAllRowExpand(true)
    }
}

// 手机号做脱敏处理
function phoneHide(phone: null | string) {
    if (phone) {
        return String(phone).replace(/(\d{3})\d*(\d{4})/, '$1****$2')
    }
    return phone
}

// 售后详情
function toSHDetail(row: ISkuOrderV0) {
    router.push({
        name: 'afterSales-detail',
        params: {
            id: row.orderLineId,
        },
    })
}
// 订单详情
function toOrderDetail(row: IRowV0) {
    router.push({
        name: 'life-mall-order-details',
        query: {
            orderId: row.id,
        },
    })
}
// 商品详情
function toGoodsDetail(row: ISkuOrderV0) {
    router.push({
        name: 'commodity-detail',
        params: {
            id: row.spuId,
            pageType: 'detail',
        },
    })
}
// 配送详情
// function lookDelivery(row: ISkuOrderV0) {
//     detailId.value = row.id
//     detailData.value = cloneDeep(row)
//     showDelivery.value = true
// }
// 确认发货
function clickShipmentsBtn(row: ISkuOrderV0, oId: number) {
    detailData.value = cloneDeep(row)
    orderLineId.value = oId
    showShipments.value = true
}
</script>

<template>
    <ElCard class="mb-20">
        <PlusForm v-model="form"
                  :columns="schema"
                  :row-props="{ gutter: 20 }"
                  label-width="80"
                  label-position="right"
        >
            <template #footer>
                <div class="ml-auto">
                    <ElButton type="primary"
                              @click="search"
                    >
                        查询
                    </ElButton>

                    <ElButton @click="reset">
                        重置
                    </ElButton>
                </div>
            </template>
        </PlusForm>
    </ElCard>

    <ElCard>
        <vxe-grid ref="xGrid"
                  v-bind="gridOptions"
        >
            <template #top>
                <el-table border
                          height="47"
                          header-row-class-name="table-row-header"
                >
                    <el-table-column v-for="(item, index) in childTableColumns"
                                     :key="index"
                                     :label="item.title"
                                     :width="item.width ?? ''"
                                     :resizable="false"
                                     align="center"
                    />
                </el-table>
            </template>

            <template #order_no="{ row }">
                订单编号：{{ row.orderCode }}
            </template>

            <template #order_time="{ row }">
                下单时间：{{ formatTime(row.createTime, 'yyyy-MM-dd HH:mm:ss') }}
            </template>

            <template #expand_content="expandRow">
                <vxe-grid v-bind="childGridOptions(expandRow.row)">
                    <template v-if="expandRow.row.skuOrderList.length > 1"
                              #bottom
                    >
                        <div class="p-10 pb-20 text-#da0004">
                            <ExpandBtn v-model="expandRow.row.isChildTableExpanded" />
                        </div>
                    </template>

                    <template #goodsInfo="{ row }">
                        <div class="flex items-center">
                            <el-image v-if="row.skuImgPath"
                                      class="mr-5 w-50"
                                      :src="row?.skuImgPath"
                                      :preview-src-list="[row?.skuImgPath]"
                                      preview-teleported
                                      fit="contain"
                            />

                            <span class="line-clamp-2 text-#da0004 text-left flex-1 cursor-pointer"
                                  @click="toGoodsDetail(row)"
                            >{{ row.skuName }}</span>
                        </div>
                    </template>

                    <template #payAmount>
                        {{ expandRow.row.orderTotalAmount }}
                    </template>

                    <template #afterSaleStatus="{ row }">
                        {{ getDictLabel('oAfterSaleStatus', row.afterSaleStatus) }}
                    </template>

                    <template #userInfo>
                        <div>
                            {{ expandRow.row.memberId }}
                        </div>

                        <el-button type="primary"
                                   link
                                   @click="expandRow.row.isShowPhone = !expandRow.row.isShowPhone"
                        >
                            {{ expandRow.row.isShowPhone ? expandRow.row.memberPhone : phoneHide(expandRow.row.memberPhone) }}
                        </el-button>
                    </template>

                    <template #receiveInfo>
                        <div class="text-left">
                            收货人：{{ expandRow.row.receiverName }} <br>
                            地址：{{ expandRow.row.orderAddress }}
                        </div>
                    </template>

                    <template #orderStatus="{ row }">
                        {{ getDictLabel('oOrderStatus', row.orderLineStatus) }}
                    </template>

                    <template #operate="{ row }">
                        <el-space>
                            <vxe-button content="查看"
                                        type="text"
                                        style="color: #da0004;"
                                        @click="toOrderDetail(expandRow.row)"
                            />

                            <vxe-button v-if="row.orderLineStatus === 1"
                                        content="确认发货"
                                        type="text"
                                        style="color: #da0004;"
                                        @click="clickShipmentsBtn(expandRow.row, row.orderLineId)"
                            />

                            <!-- <vxe-button v-else-if="row.orderLineStatus === 2"
                                        content="配送信息"
                                        type="text"
                                        style="color: #da0004;"
                                        @click="lookDelivery(row)"
                            /> -->

                            <vxe-button v-if="row.afterSaleStatus === 2"
                                        content="售后详情"
                                        type="text"
                                        style="color: #da0004;"
                                        @click="toSHDetail(row)"
                            />
                        </el-space>
                    </template>
                </vxe-grid>
            </template>

            <template #pager>
                <vxe-pager :current-page="tablePage.currentPage"
                           :page-size="tablePage.pageSize"
                           :total="tablePage.total"
                           :layouts="['Home', 'PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']"
                           background
                           @page-change="handlePageChange"
                />
            </template>
        </vxe-grid>
    </ElCard>

    <DeliveryDialog v-if="showDelivery"
                    v-model:id="detailId"
                    v-model:visible="showDelivery"
                    :data="detailData"
    />

    <ShipmentsDialog v-if="showShipments"
                     v-model:visible="showShipments"
                     :data="detailData"
                     :order-line-id="orderLineId"
                     @success="getList"
    />
</template>

<style lang="less" scoped>
:deep(.table-row-header) {
    th.el-table__cell {
        background-color: #f7f8fa;
    }

    .cell {
        line-height: 32px;
    }
}

// :deep(.vxe-body--row:nth-child(odd)) {
//     background: unset;
// }

:deep(.parent-row) {
    background: #f7f8fa;
}

:deep(.child-row) {
    background: unset;
}
</style>
